<?php

namespace app\admin\controller;


class Member extends Base
{

    // 会员列表
    public function memberlist()
    {
        $members = model('Member')->order('create_time', 'desc')->paginate(10);
        $this->assign('members', $members);
        return view();
    }


    // 会员添加
    public function memberadd()
    {
        if (request()->isAjax()) {
            $data = [
                'username' => input('post.username'),
                'password' => input('post.password'),
                'nickname' => input('post.nickname'),
                'email' => input('post.email'),
            ];
            $result = model('Member')->add($data);
            if ($result == 1) {
                $this->success('添加会员成功', 'admin/member/memberlist');
            } else {
                $this->error($result);
            }
        }

        // get请求
        return view();
    }


    // 会员编辑
    public function memberedit()
    {
        if (request()->isAjax()){
            $data = [
                'id' => input('post.id'),
                'username' => input('post.username'),
                'password' => input('post.password'),
                'new_password' => input('post.new_password'),
                'nickname' => input('post.nickname'),
                'email' => input('post.email'),
            ];
            $result = model('Member')->edit($data);
            if ($result == 1){
                $this->success('会员编辑成功', 'admin/member/memberlist');
            }else{
                $this->error($result);
            }
        }


        // get请求
        $member_info = model('Member')->find(input('post.id'));
        $this->assign('memberInfo', $member_info);
        return view();
    }

    // 删除会员
    public function memberdel()
    {
        $member = model('Member')
            ->with('comments')
            ->find(input('post.id'));
        if (!$member){
            abort('404', '该会员未找到');
        }
        // 联级删除该会员下的所有评论
        $result = $member->together('comments')->delete();
        if ($result){
            $this->success('会员删除成功', 'admin/member/memberlist');
        }else {
            $this->error('会员删除失败');
        }
    }
}
